package wzj.mybatisplusdemo.web.Interceptor;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import wzj.mybatisplusdemo.po.User;
import wzj.mybatisplusdemo.web.dto.RespEntity;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getMethod().equalsIgnoreCase("OPTIONS")){
            return true;
        }
        String jwtToken=request.getHeader("Authorization");
        System.out.println("拦截器处理jwtToken:"+jwtToken);
        if (jwtToken==null){
            String json= JSON.toJSONString(new RespEntity("4001", "请先登录", null));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;
        }
//        TODO:判断Redis里有没有jwt的key值，如果有，直接根据jwt的key的user.value，放到快递柜传到下游
        try {
            jwtToken=jwtToken.substring(7);//Bearer
            Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(jwtToken).getBody();
            System.out.println(claims);
            User u =new User();
            System.out.println(claims);
            u.setId ((int) claims.get("id"));
            u.setNickName((String) claims.get("nickName"));
            u.setLoginName((String) claims.get("loginName"));
            u.setEmail((String) claims.get("email"));
            u.setScore((int) claims.get("score"));
            request.setAttribute("curUser",u);//请求作用域(快递柜,放东西在里头，其他的方法就能取)
//            TODO:解析好之后，存到redis中，key是jwt，value是user
            return true;
        }catch (Exception e){
            String json= JSON.toJSONString(new RespEntity("4001", "凭证过期或被篡改", null));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;
        }
    }
}
